package com.heima.behavior.service.impl;

import com.heima.behavior.dtos.FollowBehaviorDto;
import com.heima.behavior.pojos.ApFollowBehavior;
import com.heima.behavior.service.ApFollowBehaviorService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.ApThreadLocalUtil;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;

import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApFollowBehaviorServiceImpl implements ApFollowBehaviorService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 关注用户
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult follow(FollowBehaviorDto dto) {

        //1. 校验参数
        if (dto.getArticleId() == null || dto.getAuthorId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2.获取登录人信息
        ApUser apUser = ApThreadLocalUtil.getUser();
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //游客身份不能进行以下操作
        if (apUser.getId() == null) {
            return ResponseResult.okResult(405,"游客身份禁止，需进行登录");
        }
        //2.判断用户和作者是否已经相互关注，查询redis
        //2.1 获取关注缓存hash类型的key
        String follow_hash_key = "USER_FOLLOW_" + apUser.getId();
        //2.2获取粉丝缓存hash类型的key
        String fans_hash_key = "USER_FANS_" + dto.getAuthorId();
        //2.3判断是否相互关注，查询关注缓存中的小key是否包含作者id
        Boolean hasKeyFlag = redisTemplate.opsForHash().hasKey(follow_hash_key, dto.getAuthorId() + "");
        //3.用户未关注
        if (!hasKeyFlag && dto.getOperation() == 0) {
            //要执行关注行为操作
            //保存数据到redis中
            redisTemplate.opsForHash().put(follow_hash_key, dto.getAuthorId() + "", "1");
            redisTemplate.opsForHash().put(fans_hash_key, apUser.getId() + "", "1");
            //保存数据到mongo中
            ApFollowBehavior behavior = new ApFollowBehavior();
            behavior.setId(ObjectId.get().toHexString());
            behavior.setArticleId(dto.getArticleId());
            behavior.setCreatedTime(new Date());
            behavior.setFollowId(dto.getAuthorId());
            behavior.setUserId(apUser.getId().longValue());
            mongoTemplate.insert(behavior);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        //4.用户已关注
        if (hasKeyFlag && dto.getOperation() == 0) {
            //表示已经关注了，无须任何操作
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        if (hasKeyFlag && dto.getOperation() == 1) {
            //表示要执行取消关注操作
            //3.1 则删除缓存数据
            redisTemplate.opsForHash().delete(follow_hash_key,dto.getAuthorId()+"");
            redisTemplate.opsForHash().delete(fans_hash_key, apUser.getId()+"");
            //3.2 删除mongodb中的数据
            Query query = Query.query(Criteria.where("userId")
                    .is(apUser.getId())
                    .and("followId").is(dto.getAuthorId()));
            mongoTemplate.remove(query, ApFollowBehavior.class);
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
